//
//  SnapView.swift
//  Dynamic
//
//  Created by Yinyin Zeng on 27/5/20.
//  Copyright © 2020 MaoYeYeDeJiangCuCha. All rights reserved.
//

import UIKit
//甩行为
class SnapView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    let squareView = UIImageView()
    var animator = UIDynamicAnimator()//需要强引用
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        
        squareView.image = UIImage(named: "Box1")
        squareView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        self.addSubview(squareView)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            let currentPoint = touch.location(in: touch.view)
            //创建动画对象
            animator = UIDynamicAnimator(referenceView: self)
            //甩行为
            let snapAction = UISnapBehavior.init(item: self.squareView, snapTo: currentPoint)
            //减速程度 越小越剧烈
            snapAction.damping = 0
            //把行为添加到动画中
            animator.addBehavior(snapAction)
        }
    }

}
